package com.live.util;

import java.util.ArrayList;


import java.util.List;


/**
 * 直播方法工具类
 */

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.live.model.v20161101.DescribeLiveStreamOnlineUserNumRequest;
import com.aliyuncs.live.model.v20161101.DescribeLiveStreamsOnlineListRequest;
import com.aliyuncs.live.model.v20161101.DescribeLiveStreamsPublishListRequest;
import com.aliyuncs.live.model.v20161101.ResumeLiveStreamRequest;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.gson.Gson;
import com.live.controller.interfaced.LiveInController;
import com.system.util.DateUtil;
import com.system.util.MD5;
import com.system.util.PageData;
import com.system.util.ToolsUtil;

public class LiveUtil extends LiveInController{
	
	
	
	private static Gson gson=new Gson();

	/**
	 * 查看推流历史
	 * 
	 * @param DomainName
	 *            直播域名
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @return
	 */
	public static String getTuiHistory(String DomainName, String startTime, String endTime) {
		HttpResponse httpResponse = new HttpResponse();
		IClientProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIWSHYz0eMok7e",
				"3cP4cK9GrmiFyBYezhRx7SpYW11kWD");
		IAcsClient client = new DefaultAcsClient(profile);
		DescribeLiveStreamsPublishListRequest describeLiveStreamsPublishListRequest = new DescribeLiveStreamsPublishListRequest();
		describeLiveStreamsPublishListRequest.setDomainName(DomainName);
		describeLiveStreamsPublishListRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
		describeLiveStreamsPublishListRequest.setEndTime(endTime + "T19:00:00Z");
		describeLiveStreamsPublishListRequest.setStartTime(startTime + "T19:00:00Z");
		System.out.println("版本:"+describeLiveStreamsPublishListRequest.getVersion());
		try {
			httpResponse = client.doAction(describeLiveStreamsPublishListRequest);
		
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return new String(httpResponse.getHttpContent());
	}

	public static String addLaAddress(String tuiAddress) {
		HttpResponse httpResponse = new HttpResponse();
		IClientProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIWSHYz0eMok7e","3cP4cK9GrmiFyBYezhRx7SpYW11kWD");
		IAcsClient client = new DefaultAcsClient(profile);
		ResumeLiveStreamRequest resumeLiveStreamRequest = new ResumeLiveStreamRequest();
		resumeLiveStreamRequest.setDomainName(tuiAddress);
		resumeLiveStreamRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
		resumeLiveStreamRequest.setAppName("ZSHApp");
		resumeLiveStreamRequest.setLiveStreamType("publisher");
		resumeLiveStreamRequest.setStreamName("roomid");
		
		try {
			httpResponse = client.doAction(resumeLiveStreamRequest);
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return new String(httpResponse.getHttpContent());
	}

	
	
	/**
	 * 获取一个拉流
	 * @param AppName     App名称用作拉流地址
	 * @param StreamType  拉流所属类型(game游戏,music唱歌等等自定义类型就可以)
	 * @return
	 */
	public synchronized static PageData getPullAddress(String AppName,String StreamName) {
		PageData pd = new PageData();
		String pullAddress="rtmp://live.rongyaohk.com/" + AppName + "/" + StreamName + "?auth_key="+getAuth_Key(3600, AppName, StreamName, "zsh2018");
		pd.put("PublishUrl", pullAddress);
		return pd;
	}
	
	/**
	 * api:https://help.aliyun.com/document_detail/35409.html?spm=a2c4g.11186623.2.39.2DHOA9
	 * 获取所有在线的推流地址
	 * @param DomainName   直播域名
	 * @param AppName      App名称
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static PageData getPushOnline(String DomainName, String AppName) {
		HttpResponse httpResponse = new HttpResponse();
		IClientProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIWSHYz0eMok7e",
				"3cP4cK9GrmiFyBYezhRx7SpYW11kWD");
		IAcsClient client = new DefaultAcsClient(profile);
		DescribeLiveStreamsOnlineListRequest describeLiveStreamsOnlineListRequest = new DescribeLiveStreamsOnlineListRequest();
		describeLiveStreamsOnlineListRequest.setDomainName(DomainName);
		describeLiveStreamsOnlineListRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
		PageData pd = new PageData();
		try {
			httpResponse = client.doAction(describeLiveStreamsOnlineListRequest);
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		String OnlineInfo = new String(httpResponse.getHttpContent());
		PageData fromJson = gson.fromJson(OnlineInfo, PageData.class);
		String json = gson.toJson(fromJson.get("OnlineInfo"));
		PageData fromJson2 = gson.fromJson(json, PageData.class);
		 List<PageData> list=new ArrayList<>();
		if (fromJson2.get("LiveStreamOnlineInfo")!=null) {
        list= (List<PageData>) fromJson2.get("LiveStreamOnlineInfo");
        String json2 = gson.toJson(list);
        try {
			list = ToolsUtil.fromJson(json2, PageData.class);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        for (PageData pageData : list) {
    		pageData.remove("AppName");
    		pageData.remove("DomainName");
    		pageData.remove("PublishDomain");
    		pageData.put("UserNumber", getUserOnline(DomainName, AppName, pageData.getString("StreamName")));
    		pageData.put("PublishUrl", pageData.get("PublishUrl")+"?auth_key="+getAuth_Key(3600, AppName, pageData.getString("StreamName"), "zsh2018"));
    		pageData.remove("StreamName");
    		}
		}
		
		fromJson2.put("LiveStreamOnlineInfo", list);
		fromJson.put("OnlineInfo", fromJson2);
		pd.put("PUSHONLINE", gson.toJson(fromJson));
		return pd;
	}
	
	
	
	/**
	 * 查询在线人数
	 * api:https://help.aliyun.com/document_detail/35412.html?spm=a2c4g.11186623.2.79.uNZCZm
	 * @param DomainName   直播域名
	 * @param AppName      App应用名称
	 * @param StreamName   直播流名称
	 * @return
	 */
	public static String getUserOnline(String DomainName, String AppName,String StreamName) {
		HttpResponse httpResponse = new HttpResponse();
		IClientProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIWSHYz0eMok7e",
				"3cP4cK9GrmiFyBYezhRx7SpYW11kWD");
		IAcsClient client = new DefaultAcsClient(profile);
		DescribeLiveStreamOnlineUserNumRequest describeLiveStreamOnlineUserNumRequest = new DescribeLiveStreamOnlineUserNumRequest();
		describeLiveStreamOnlineUserNumRequest.setDomainName(DomainName);//播放域名(直播域名)
		describeLiveStreamOnlineUserNumRequest.setAppName(AppName);//App名称
		describeLiveStreamOnlineUserNumRequest.setStreamName(StreamName);//流类型。取值范围：
		describeLiveStreamOnlineUserNumRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
		String UserNumber="";
		try {
			httpResponse = client.doAction(describeLiveStreamOnlineUserNumRequest);
			System.out.println("在线人数返回:"+new String(httpResponse.getHttpContent()));
			String string = new String(httpResponse.getHttpContent());
			PageData fromJson = gson.fromJson(string, PageData.class);
			String json = gson.toJson(fromJson.get("OnlineUserInfo"));
			try {
				PageData pageData = gson.fromJson(json, PageData.class);
				String json2 = gson.toJson(pageData.get("LiveStreamOnlineUserNumInfo"));
				List<PageData> list = ToolsUtil.fromJson(json2, PageData.class);
				for (PageData pageData2 : list) {
					  UserNumber=pageData2.get("UserNumber").toString();//直播流的在线人数
					  System.out.println("num:"+UserNumber);
				}
			   
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return UserNumber.toString();
	}
	
	
	
	
	/**
	 * 生成Auth_Key工具
	 * @param secondtime      过期时间/秒
	 * @param AppName         应用名称，用于生成地址
	 * @param StreamName      每个推流独立Name
	 * @param authkey         用户自定义鉴权Key,需和阿里云保持同步
	 * @return
	 */
	public static String getAuth_Key(Integer secondtime,String AppName,String StreamName,String authkey){
		String HashValue = MD5.md5("/"+AppName+"/"+StreamName+"-"+DateUtil.getUnixTime(DateUtil.getTimeWithSecond(secondtime))+"-0-0-"+authkey);
		String auth_key=DateUtil.getUnixTime(DateUtil.getTimeWithSecond(secondtime))+"-0-0-"+HashValue;
		return auth_key;
	}

	public static void main(String[] args) {
		// 推流历史测试
		
		/*  String tuiHistory = new LiveUtil().getTuiHistory("live.rongyaohk.com", "2018-01-15", "2018-01-18"); 
		  System.out.println(tuiHistory);*/
		 
		/*
		 * String addLaAddress = new Test().addLaAddress("live.rongyaohk.com");
		 * System.out.println(addLaAddress);
		 */
		/*PageData pd= new LiveUtil().getPushAddress("ZSHApp", "roomid");
		System.out.println("推流地址:"+pd);
		PageData pd1= new LiveUtil().getPushOnline("live.rongyaohk.com", "ZSHApp");
		//rtmp://live.rongyaohk.com/ZSHApp/roomid?auth_key=1516334060-0-0-r
		System.out.println(pd1);*/
		/*String pullAddress = new LiveUtil().getPullAddress("ZSHApp", "roomid");
		System.out.println("拉流地址:"+pullAddress);*/
		//查询在线人数
		/*new LiveUtil().getPersonOnline("live.rongyaohk.com", "ZSHApp", StreamName);*/
	}
}
